<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!doctype html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 上述3个meta标签*必须*放在最前面，任何其他内容都*必须*跟随其后！ -->
    <title>msgSend</title>
    <!-- Bootstrap -->
    <link rel="stylesheet" href="../commons/bootstrap-3.3.7-dist/css/bootstrap.min.css">
    <!-- 加载bootstrap-select -->
    <link href="../commons/bootstrap-select-1.13.9-dist/css/bootstrap-select.min.css" rel="stylesheet">
    <!-- 加载bootstrap-treeview -->
    <link href="../commons/bootstrap-treeview-1.2.0-dist/bootstrap-treeview.min.css" rel="stylesheet">
    <link rel="stylesheet" href="../commons/css/currency.css">


    <!-- HTML5 shim 和 Respond.js 是为了让 IE8 支持 HTML5 元素和媒体查询（media queries）功能 -->
    <!-- 警告：通过 file:// 协议（就是直接将 html 页面拖拽到浏览器中）访问页面时 Respond.js 不起作用 -->
    <!--[if lt IE 9]>
    <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
    <![endif]-->
</head>
<body>
<nav class="navbar navbar-default" role="navigation">
    <div class="container-fluid">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#example-navbar-collapse">
                <span class="sr-only">切换导航</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">CIMS-校园即时通讯系统</a>
        </div>
        <div class="collapse navbar-collapse" id="example-navbar-collapse">
            <ul class="nav navbar-nav">
                <li class="active"><a href="msgIndex">首页</a></li>
                <li class=""><a href="msgSend">发消息</a></li>
                <li class=""><a href="msgReceive"><span id="noAnswerCount" class="badge pull-right" style="background-color:red"></span>收消息</a></li>
            </ul>
            <ul class="nav navbar-nav" style="float: right">
                <li class=""><a id="loginUser_nav"></a></li>
                <li class=""><a id="logout_nav">注销</a></li>
            </ul>
        </div>
    </div>
</nav>

<div class="container">
    <div class="page-header">
        <h3 style="align-content: center">发送消息</h3>
    </div>


    <table class="table table-striped table-bordered" id="msgs-table">
        <thead>
        <tr>
            <th scope="col" class="col-lg-3">标题</th>
            <th scope="col" class="col-lg-3">时间</th>
            <th scope="col" class="col-lg-2">类型</th>
            <th scope="col" class="col-lg-4">操作</th>
        </tr>
        </thead>
        <tbody>
        </tbody>
        <tfoot>
        </tfoot>
    </table>

    <!-- 模态框（Modal） -->
    <div class="modal fade" id="msg_send_modal" tabindex="-1" role="dialog" aria-labelledby="msg_send_modal"
         aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title"> 发送消息</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal" role="form" id="msg_send_frm">
                        <div class="form-group">
                            <label class="col-sm-3 control-label"> 类型：</label>
                            <div class="col-sm-8">
                                <select class="selectpicker form-control" name="msgType" title="请选择消息类型"
                                        id="msgType_send_modal">
                                    <option value="1"> 消息</option>
                                    <option value="2"> 通知</option>
                                    <option value="3"> 投票</option>
                                </select>
                                <span class="help-block"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="msgTitle_send_modal" class="col-sm-3 control-label"> 标题：</label>
                            <div class="col-sm-8">
                                <input type="text" class="form-control" name="msgTitle" id="msgTitle_send_modal"
                                       placeholder="请输入消息标题">
                                <span class="help-block"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label"> 接收对象：</label>
                            <div class="col-sm-8">
                                <div id="user_tree"></div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="msgContent_send_modal" class="col-sm-3 control-label"> 内容：</label>
                            <div class="col-sm-8">
                                <textarea class="form-control" rows="3" name="msgContent" id="msgContent_send_modal"
                                          placeholder="请输入消息内容"></textarea>
                                <span class="help-block"></span>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal"> 关闭</button>
                    <button type="button" class="btn btn-primary" id="msg_add_btn"> 保存</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal -->
    </div>

    <!-- 查看模态框（Modal） -->
    <div class="modal fade" id="msg_see_modal" tabindex="-1" role="dialog" aria-labelledby="msg_see_modal"
         aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="title_see_modal"> 查看消息</h4>
                </div>
                <div class="modal-body" id="msgDiv_see_modal">

                    <p id="msgContent_see_modal"></p>

                    <table class="table table-bordered table-striped table-hover" id="answerMsgs-table">
                        <thead>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                    <canvas id="myChart"></canvas>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal"> 关闭</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal -->
    </div>

    <div class="footer ">
        <div class="container">
            <div class="row footer-bottom">
                <ul class="list-inline text-center">
                    <li> Campus Instant Messaging System @2020 杭州职业技术学院 软件技术专业</li>
                </ul>
            </div>
        </div>
    </div>
</div>
<!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery，所以必须放在前边) -->
<script src="../commons/js/jquery.js"></script>
<!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
<script src="../commons/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
<script src="../commons/bootstrap-treeview-1.2.0-dist/bootstrap-treeview.min.js"></script>
<script src="../commons/bootstrap-select-1.13.9-dist/js/bootstrap-select.min.js"></script>
<!--加载chart.js -->
<script src="../commons/Chart.js-2.9.3/dist/Chart.min.js"></script>
<script src="../commons/Chart.js-2.9.3/samples/utils.js"></script>
<script src="../commons/js/login.js"></script>
<script src="../commons/js/utils.js"></script>

<script>
    var pn;
    $(function () {
        load_noAnswer_Count();
        pn = 1;
        to_page(pn);
    });

    //导航栏未读消息提示
    function load_noAnswer_Count() {
        $.ajax({
            url: "noAnswerCount",
            type: "GET",
            dataType: "json",
            success: function (result) {
                if (result.code == 100) {
                    //查询成功，解析并显示数据
                    $("#noAnswerCount").empty().append(result.extend.noAnswerCount);
                } else {

                }

            }
        })
    }
    function to_page(pn) {
        $.ajax({
            url: "msgs",
            type: "GET",
            data: {"pn": pn},
            dataType: "json",
            beforeSend: function () {
                $("#msgs-table tbody").empty();
                $("#msgs-table tfoot").empty();
                $("#msgs-table tbody").append("<tr><td colspan='4'>正在加载数据，请稍后...</td></tr>");
            },
            success: function (result) {
                if (result.code == 100) {
                    //查询成功，解析并显示数据
                    //1、显示消息信息
                    build_msgs_table(result);
                    //2、显示分页信息
                    build_page_nav(result);
                } else {

                }
            },
            error: function () {
                $("#msgs-table tbody").empty();
                $("#msgs-table tfoot").empty();
                $("#msgs-table tbody").append("<tr><td colspan='4'>查询出错，请稍后再试！</td></tr>");
            }
        });
    }

    function build_msgs_table(result) {
        $("#msgs-table tbody").empty();
        var msgs = result.extend.pageInfo.list;
        $.each(msgs, function (index, msg) {
            var msgTitleTd = $("<td></td>").append(msg.msgTitle);
            var msgSendTimeTd = $("<td></td>").append(msg.msgSendTime);
            var msgTypeTd = $("<td></td>").addClass("tdCenter").append(msg.msgTypeText);
            var seeBtn = $("<button></button>").addClass("btn btn-sm btn-warning see_btn")
                .append($("<span></span>").addClass("glyphicon glyphicon-eye-open")).append(" 查看");
            seeBtn.attr({"see-id": msg.id, "pn": result.extend.pageInfo.pageNum});
            var editBtn = $("<button></button>").addClass("btn btn-sm btn-primary edit_btn")
                .append($("<span></span>").addClass("glyphicon glyphicon-edit")).append(" 修改");
            editBtn.attr({"edit-id": msg.id, "pn": result.extend.pageInfo.pageNum});
            var delBtn = $("<button></button>").addClass("btn btn-sm btn-danger delete_btn")
                .append($("<span></span>").addClass("glyphicon glyphicon-remove")).append(" 删除");
            delBtn.attr("delete-id", msg.id);
            var msgOperationDiv = $("<div></div>").addClass("input-group").append($("<span></span>").addClass("input-group-btn").append(seeBtn).append(editBtn).append(delBtn));
            var msgOperationTd = $("<td></td>").addClass("tdCenter").append(msgOperationDiv);

            $("<tr></tr>").append(msgTitleTd)
                .append(msgSendTimeTd)
                .append(msgTypeTd)
                .append(msgOperationTd)
                .appendTo("#msgs-table tbody");
        });
    }

    function build_page_nav(result) {
        $("#msgs-table tfoot").empty();

        var addLi = $("<li></li>").append($("<a></a>").attr("id", "msg_send_btn").append($("<span></span>").addClass("glyphicon glyphicon-plus").append("新消息")));
        var operatorUl = $("<ul></ul>").addClass("pagination pull-left").attr("style", "margin: 0 0 0 0;");
        operatorUl.append(addLi);

        var pageUl = $("<ul></ul>").addClass("pagination").attr("style", "margin: 0 0 0 0;");
        var firstPageLi = $("<li></li>").append($("<a></a>").append("首页"));
        ;
        if (result.extend.pageInfo.isFirstPage) {
            firstPageLi.addClass("disabled");
        } else {
            firstPageLi.click(function () {
                to_page(2);
            });
        }
        pageUl.append(firstPageLi);

        var previousPageLi = $("<li></li>").append($("<a></a>").append("《"));
        if (result.extend.pageInfo.hasPreviousPage) {
            previousPageLi.click(function () {
                to_page(result.extend.pageInfo.pageNum - 1);
            });
        } else {
            previousPageLi.addClass("disabled");
        }
        pageUl.append(previousPageLi);
        $.each(result.extend.pageInfo.navigatepageNums, function (index, npNum) {
            var pageLi = $("<li></li>").append($("<a></a>").append(npNum));
            if (result.extend.pageInfo.pageNum == npNum) {
                pageLi.addClass("active");
            } else {
                pageLi.click(function () {
                    to_page(npNum);
                });
            }
            pageUl.append(pageLi);
        });
        var nextPageLi = $("<li></li>").append($("<a></a>").append("》"));
        if (result.extend.pageInfo.hasNextPage) {
            nextPageLi.click(function () {
                to_page(result.extend.pageInfo.pageNum + 1);
            });
        } else {
            nextPageLi.addClass("disabled");
        }
        pageUl.append(nextPageLi);
        var lastPageLi = $("<li></li>").append($("<a></a>").append("末页"));
        if (result.extend.pageInfo.isLastPage) {
            lastPageLi.addClass("disabled");
        } else {
            lastPageLi.click(function () {
                to_page(result.extend.pageInfo.pages);
            });
        }
        pageUl.append(lastPageLi);
        var pageInfoUl = $("<ul></ul>").addClass("pagination pull-right").attr("style", "margin: 0 0 0 0;")
        var pageInfoLi = $("<li></li>").addClass("disabled").append($("<a></a>").attr("style", "border: 0px").append("当前第 " + result.extend.pageInfo.pageNum + " 页，总 "
            + result.extend.pageInfo.pages + " 页，总 "
            + result.extend.pageInfo.total + " 条记录"));
        pageInfoUl.append(pageInfoLi);

        pn = result.extend.pageInfo.pageNum;

        var pageNavTd = $("<td></td>").addClass("text-center")
            .attr({"colspan": 5}).append(operatorUl).append(pageUl).append(pageInfoUl);

        $("<tr></tr>").append(pageNavTd)
            .appendTo("#msgs-table tfoot");
    }


    $(document).on("click", ".delete_btn", function () {
        var msgTitle = $(this).parents("tr").find("td:eq(0)").text();
        if (confirm("确认删除[ " + msgTitle + " ]吗？")) {
            $.ajax({
                url: "msg/" + $(this).attr("delete-id"),
                type: "DELETE",
                dataType: "json",
                success: function (result) {
                    alert(result.msg);
                    if (result.code = 100) {
                        //删除成功
                        //刷新单位列表显示
                        to_page(1);
                    }
                }
            });
        }
    });

    $(document).on("click", "#msg_send_btn", function () {
        $.ajax({
            url: "userUnits",
            type: "GET",
            dataType: "json",
            success: function (result) {
                $('#user_tree').treeview({
                    data: result.extend.units,
                    levels: 1,
                    showCheckbox: 'true',
                    onNodeChecked: function (event, node) {
                        if (node.unitName != undefined) {
                            $.each(node.nodes, function (index, sonNode) {
                                $('#user_tree').treeview("checkNode", sonNode.nodeId, {silent: true});
                            });
                        }
                    },
                    onNodeUnchecked: function (event, node) {
                        if (node.unitName != undefined) {
                            $.each(node.nodes, function (index, sonNode) {
                                $('#user_tree').treeview("uncheckNode", sonNode.nodeId, {silent: true});
                            });
                        }
                    }
                });
            }

        });

        $("#msg_send_modal").modal({
            "backdrop": "static"
        });
    });

    $("#msg_add_btn").click(function () {
        //校验数据
        $("input[name='receiveUserId']").remove();

        //获取选择用户id
        var checkedNodes = $('#user_tree').treeview("getChecked");
        $.each(checkedNodes, function (index, node) {
            if (node.userName != undefined) {
                $("<input></input>").attr({
                    "type": "hidden",
                    "name": "receiveUserId"
                }).val(node.id).appendTo("#msg_send_frm");
            }
        });

        //添加
        $.ajax({
            url: "msg",
            data: $("#msg_send_frm").serialize(),
            type: "post",
            dataType: "json",
            success: function (result) {
                if (result.code == 100) {
                    //添加成功，刷新所有地域信息
                    $("#msg_send_modal").modal('hide');
                    alert("消息信息发送成功！");
                    to_page(1);
                }
            }
        });
    });

    $(document).on('hidden.bs.modal', '.modal', function () {
        $("#msg_send_modal form")[0].reset();
        $("#msg_send_modal form").find("*").removeClass("has-error has-success");
        $("#msg_send_modal form").find(".help-block").text("");
        $("#msgType_send_modal").selectpicker("refresh");
    });

    $(document).on("click", ".see_btn", function () {

        $.ajax({
            url: "msg/" + $(this).attr("see-id"),
            type: "GET",
            dataType: "json",
            success: function (result) {
                if (result.code == 100) {
                    var msg = result.extend.msg;
                    //消息头部信息
                    $("#title_see_modal").empty()
                        .append(msg.msgTitle)
                        .append("<br>")
                        .append($("<small></small>").append($("<strong></strong>").append(" [ " + msg.msgTypeText + " ] "))
                            .append("  " + msg.msgSendTime));
                    $("#msgContent_see_modal").empty().append(msg.msgContent);
                    //消息接收回复信息
                    build_answerMsgs_table(result);
                    //消息统计图表
                    initMyChart(result);
                }
            }
        });

        $("#msg_see_modal").modal({
            "backdrop": "static"
        });
    });

    function build_answerMsgs_table(result) {
        $("#answerMsgs-table thead").empty();
        var msg = result.extend.msg;
        if (msg.msgType == 1) {
            $("#answerMsgs-table thead").append($("<tr><th>接收人</th><th>状态</th><th>查收时间</th></tr>"));
        } else if (msg.msgType == 2) {
            $("#answerMsgs-table thead").append($("<tr><th>接收人</th><th>状态</th><th>回复时间</th><th>回复内容</th></tr>"));
        } else {
            $("#answerMsgs-table thead").append($("<tr><th>接收人</th><th>状态</th><th>投票时间</th><th>投票原因</th></tr>"));
        }
        var answerMsgs = result.extend.msg.msgAnswers;
        $("#answerMsgs-table tbody").empty();
        $.each(answerMsgs, function (index, answerMsg) {
            if (msg.msgType == 1) {
                var msgReceiveUserTd = $("<td></td>").append(answerMsg.receiveUser.userName);
                var msgStateTd = $("<td></td>");
                if (answerMsg.msgState == 0) {
                    msgStateTd.append("未查收");
                } else {
                    msgStateTd.append("已查收");
                }
                var msgAnswerTimeTd = $("<td></td>").addClass("tdCenter").append(answerMsg.msgAnswerTime);

                var msgTr = $("<tr></tr>");
                if (answerMsg.msgState == 0) {
                    msgTr.addClass("danger")
                } else {
                    msgTr.addClass("success")
                }
                msgTr.append(msgReceiveUserTd)
                    .append(msgStateTd)
                    .append(msgAnswerTimeTd)
                    .appendTo("#answerMsgs-table tbody");
            } else if (msg.msgType == 2) {
                var msgReceiveUserTd = $("<td></td>").append(answerMsg.receiveUser.userName);
                var msgStateTd = $("<td></td>");
                if (answerMsg.msgState == 0) {
                    msgStateTd.append("未回复");
                } else {
                    msgStateTd.append("已回复");
                }
                var msgAnswerTimeTd = $("<td></td>").addClass("tdCenter").append(answerMsg.msgAnswerTime);
                var msgAnswerContentTd = $("<td></td>").append(answerMsg.msgAnswerContent);

                var msgTr = $("<tr></tr>");
                if (answerMsg.msgState == 0) {
                    msgTr.addClass("danger")
                } else {
                    msgTr.addClass("success")
                }
                msgTr.append(msgReceiveUserTd)
                    .append(msgStateTd)
                    .append(msgAnswerTimeTd)
                    .append(msgAnswerContentTd)
                    .appendTo("#answerMsgs-table tbody");
            } else {
                var msgReceiveUserTd = $("<td></td>").append(answerMsg.receiveUser.userName);
                var msgStateTd = $("<td></td>");
                if (answerMsg.msgState == 0) {
                    msgStateTd.append("未投票");
                } else {
                    if (answerMsg.msgVote == 0) {
                        msgStateTd.append("反对");
                    } else {
                        msgStateTd.append("赞成");
                    }
                }
                var msgAnswerTimeTd = $("<td></td>").addClass("tdCenter").append(answerMsg.msgAnswerTime);
                var msgVoteReasonTd = $("<td></td>").append(answerMsg.msgVoteReason);

                var msgTr = $("<tr></tr>");
                if (answerMsg.msgState == 0) {
                    msgTr.addClass("danger")
                } else {
                    if (answerMsg.msgVote == 0) {
                        msgTr.addClass("warning")
                    } else {
                        msgTr.addClass("success")
                    }
                }
                msgTr.append(msgReceiveUserTd)
                    .append(msgStateTd)
                    .append(msgAnswerTimeTd)
                    .append(msgVoteReasonTd)
                    .appendTo("#answerMsgs-table tbody");
            }
        });
    }

    function initMyChart(result) {
        $("#myChart").remove();
        $("#msgDiv_see_modal").append("<canvas id='myChart'></canvas>");
        var ctx = document.getElementById('myChart').getContext('2d');
        var chart = new Chart(ctx, {
            type: 'doughnut',
            data: {
                datasets: [{
                    data: result.extend.msgCounts,
                    backgroundColor: [
                        window.chartColors.red,
                        window.chartColors.yellow,
                        window.chartColors.blue
                    ],
                    label: '消息状况'
                }],
                labels: result.extend.msgTexts
            },

            options: {
                responsive: true,
                legend: {
                    position: 'right',
                },
                title: {
                    display: false,
                    text: '消息状态统计'
                },
                animation: {
                    animateScale: true,
                    animateRotate: true
                },

            }
        });
    }
</script>
</body>
</html>
